package com.teaching.management.controller.api;

import com.teaching.management.entity.Course;
import com.teaching.management.entity.User;
import com.teaching.management.repository.ClassroomRepository;
import com.teaching.management.repository.CourseRepository;
import com.teaching.management.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;

/**
 * 课程管理相关的REST API
 */
@RestController
@RequestMapping("/api/admin/courses")
public class AdminCourseRestController {

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private ClassroomRepository classroomRepository;

    /**
     * 获取所有课程
     */
    @GetMapping
    public ResponseEntity<?> getAllCourses(HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        List<Course> courses = courseRepository.findAll();
        return ResponseEntity.ok(courses);
    }

    /**
     * 根据条件搜索课程
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchCourses(@RequestParam("term") String searchTerm, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 创建模糊匹配，匹配课程编号或课程名称
        Course example = new Course();
        example.setCourseId(searchTerm);
        example.setName(searchTerm);

        ExampleMatcher matcher = ExampleMatcher.matchingAny()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();

        List<Course> courses = courseRepository.findAll(Example.of(example, matcher));
        return ResponseEntity.ok(courses);
    }

    /**
     * 获取单个课程详情
     */
    @GetMapping("/{courseId}")
    public ResponseEntity<?> getCourse(@PathVariable String courseId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        Optional<Course> courseOpt = courseRepository.findById(courseId);
        if (courseOpt.isPresent()) {
            return ResponseEntity.ok(courseOpt.get());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("课程不存在");
        }
    }

    /**
     * 添加新课程
     */
    @PostMapping
    public ResponseEntity<?> addCourse(@RequestBody Course course, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查课程ID是否已存在
        if (courseRepository.existsById(course.getCourseId())) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("课程编号已存在");
        }

        // 检查教师是否存在
        if (!teacherRepository.existsById(course.getTeacherId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的教师不存在");
        }

        // 检查教室是否存在
        if (!classroomRepository.existsById(course.getClassroomId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的教室不存在");
        }

        Course savedCourse = courseRepository.save(course);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedCourse);
    }

    /**
     * 更新课程信息
     */
    @PutMapping("/{courseId}")
    public ResponseEntity<?> updateCourse(
            @PathVariable String courseId,
            @RequestBody Course course,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 确保路径中的ID与请求体中的ID一致
        if (!courseId.equals(course.getCourseId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("课程编号不一致");
        }

        // 检查课程是否存在
        if (!courseRepository.existsById(courseId)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("课程不存在");
        }

        // 检查教师是否存在
        if (!teacherRepository.existsById(course.getTeacherId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的教师不存在");
        }

        // 检查教室是否存在
        if (!classroomRepository.existsById(course.getClassroomId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的教室不存在");
        }

        Course updatedCourse = courseRepository.save(course);
        return ResponseEntity.ok(updatedCourse);
    }

    /**
     * 删除课程
     */
    @DeleteMapping("/{courseId}")
    public ResponseEntity<?> deleteCourse(@PathVariable String courseId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查课程是否存在
        if (!courseRepository.existsById(courseId)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("课程不存在");
        }

        try {
            courseRepository.deleteById(courseId);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 可能因为外键约束而无法删除
            return ResponseEntity.status(HttpStatus.CONFLICT)
                    .body("删除失败，该课程已被学生选择，请先解除关联");
        }
    }

    /**
     * 获取所有教师列表，用于课程管理页面中的选择框
     */
    @GetMapping("/teachers")
    public ResponseEntity<?> getAllTeachers(HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        return ResponseEntity.ok(teacherRepository.findAll());
    }

    /**
     * 获取所有教室列表，用于课程管理页面中的选择框
     */
    @GetMapping("/classrooms")
    public ResponseEntity<?> getAllClassrooms(HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        return ResponseEntity.ok(classroomRepository.findAll());
    }
}